<template>
  <div class="event-info">
    <el-form :model="ruleForm" :rules="rules" ref="PublishForm" label-width="100px" label-suffix="：">
      <div class="event-content">
        <el-form-item label="上级分类" prop="sortCode">
          <div class="cont-input">
            <el-cascader
              v-model="ruleForm.sortCode"
              :change-on-select="true"
              :options="sortData"
              :props="propData"
              clearable>
            </el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="信息标题" prop="title">
          <div class="cont-input">
            <el-input v-model="ruleForm.title" placeholder="请输入信息标题"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="信息图片" prop="thumbSrc">
          <UpLoad 
            v-model="ruleForm.thumbSrc" 
            :limit="thumbSrcProp.limit"
            :editId="editId"
            :type="thumbSrcProp.type"
            :filelist="filelist"
            @geturl="getPictureUrl"
          />
        </el-form-item>
        <el-form-item label="排序" prop="orderId">
          <div class="cont-input">
             <el-input v-model="ruleForm.orderId" placeholder="请输入排序"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="关键字" prop="keyword">
          <div class="cont-input">
             <el-input v-model="ruleForm.keyword" placeholder="请输入网站关键字"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="描述" prop="resume">
          <div class="cont-input">
            <el-input v-model="ruleForm.resume" type="textarea" placeholder="请输入描述"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="文章标签" prop="tagNames">
          <div class="cont-input">
             <el-select
              v-model="ruleForm.tagNames"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择文章标签"
              >
                <el-option
                  v-for="(todo,index) in tagsList"
                  :key="index"
                  :label="todo.tagName"
                  :value="todo.tagName">
                </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="isActivity">
          <div class="cont-input">
            <el-switch
              v-model="ruleForm.isActivity"
              active-value="1"
              inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </div>
        </el-form-item>
        <template v-if="commonTabInfo.text === '编辑' && editData.sortCode == 'info'">
          <el-form-item label="预览">
            <div class="cont-input">
              <el-link type="primary" :href="'http://dfyz.cn.com:8201/pages/newsInfo/newsInfo.html?code='+editData.id" target="_blank">点击查看文章</el-link>
            </div>
          </el-form-item>
        </template>
        <el-form-item label="详细内容" prop="content">
          <quillEditor 
            v-loading="quillUpdateImg"
            :options="editorOption"
            v-model="ruleForm.content"
            ref="myQuillEditor"
            @blur="onEditorBlur($event)" 
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)">
          </quillEditor>
          <!-- 图片上传组件辅助-->
          <div id="quill-upload" v-show="false">
            <el-upload
              class="avatar-uploader"
              :action="serverImgUrl"
              :multiple="true"
              name="file"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :before-upload="beforeUpload">
            </el-upload>
          </div>
        </el-form-item>
      </div>
      <div class="cont-footer">
        <el-button @click.native="cancelPop">取消</el-button>
        <template v-if="commonTabInfo.text === '新增'">
          <el-button type="primary" @click.native="addPublishEvent">保存</el-button>
        </template>
        <template v-else-if="commonTabInfo.text === '编辑'">
          <el-button type="primary" @click.native="editPublishEvent">保存编辑</el-button>
        </template>
      </div>
    </el-form>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import UploadPicUrl, { AddOrUpdatePublishInfo, GetPublishInfoSingle, GetPublishSortTable, DeletePic, GetTagQuerylist } from '@/api/requestConfig'
  import { getTreeDeepArr } from '@/utils/index' // 递归获取数组
  import { quillEditor } from 'vue-quill-editor'
  import UpLoad from '@/components/Upload'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  export default {
    name: 'PublishInfo',
    data() {
      return {
        propData: {
          value: 'sortCode',
          label: 'sortName',
          children: 'data'
        }, // 上级菜单配置
        sortData: [],
        editId: 0, // 编辑Id
        filelist: [], // 编辑图片
        thumbSrcProp: {
          type: 1, // 消息发布1；合作伙伴2；广告3；
          limit: 2
        }, // 图片上传组件参数
        ruleForm: {
          sortCode: [],
          isActivity: '1',
          title: '',
          resume: '',
          keyword: '',
          orderId: '',
          thumbSrc: '',
          content: '',
          tagNames: [] // 标签
        },
        rules: {
          title: [
            { required: true, message: '请输入信息标题', trigger: 'blur' }
          ],
          sortCode: [
            { required: true, message: '请选择信息分类', trigger: 'change' }
          ]
        },
        tagsList: [], // 标签列表
        editData: {},
        addFlag: true,
        editorOption: {
          // some quill options
          modules: {
            toolbar: {
              container: [
                ['bold', 'italic', 'underline', 'strike'], // toggled buttons
                ['blockquote', 'code-block'],
                ['link', 'image', 'video'],
                [{ 'header': 1 }, { 'header': 2 }], // custom button values
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                [{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
                [{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
                [{ 'direction': 'rtl' }], // text direction
                [{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                [{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
                [{ 'font': [] }],
                [{ 'align': [] }],
                ['clean'] // remove formatting button
              ],
              handlers: {
                'image': function(value) {
                  if (value) {
                    document.querySelector('#quill-upload input').click()
                  } else {
                    this.quill.format('image', false)
                  }
                }
              }
            }
          }
        },
        serverImgUrl: UploadPicUrl + '?type=1', // 图片上传地址
        quillUpdateImg: false // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
      }
    },
    computed: {
      ...mapGetters([
        'commonTabInfo'
      ])
    },
    components: {
      quillEditor,
      UpLoad
    },
    created() {
      // 获取菜单数据
      GetPublishSortTable().then(res => {
        if (res.data) {
          this.sortData = res.data
        }
      }).then(() => {
        if (this.commonTabInfo.text === '编辑') {
          this.editId = this.commonTabInfo.custom.id
          GetPublishInfoSingle(this.editId).then(res => {
            if (res.data) {
              const resData = res.data
              this.editData = resData
              if (this.editData) {
                for (var key in this.ruleForm) {
                  if (key === 'sortCode') {
                    this.ruleForm.sortCode = getTreeDeepArr(resData.sortCode, 'sortCode', this.sortData, 'data') // 渲染上级选择的菜单
                    console.log(getTreeDeepArr(resData.sortCode, 'sortCode', this.sortData, 'data'))
                  } else if (key === 'isActivity') {
                    this.ruleForm[key] = String(this.editData[key])
                  } else if (key === 'tagNames' && this.editData[key]) {
                    this.ruleForm[key] = this.editData[key].split(',')
                  } else {
                    this.ruleForm[key] = this.editData[key]
                  }
                }
                console.log(this.ruleForm)
                // 渲染图片
                if (this.ruleForm.thumbSrc) {
                  var resultList = []
                  var srcArr = this.ruleForm.thumbSrc.split(',')
                  for (var i = 0; i < srcArr.length; i++) {
                    var obj = {}
                    obj.name = srcArr[i]
                    obj.url = srcArr[i]
                    resultList.push(obj)
                  }
                  this.filelist = resultList
                  this.ruleForm.thumbSrc = resultList
                }
              }
              console.log(this.ruleForm)
            }
          })
        }
      })
      // 获取标签库
      GetTagQuerylist().then(res => {
        if (res.data) {
          this.tagsList = res.data
          console.log(this.tagsList)
        }
      })
    },
    methods: {
      // tabs操作
      eventTab(text, tabsName, custom) {
        this.$store.dispatch('handleTabInfo', {
          text: text,
          tabsName: tabsName,
          custom: custom
        })
      },
      // 取消
      cancelPop() {
        // 新增时如果上传了图片，需删除
        var self = this
        if (this.commonTabInfo.text === '新增') {
          var picUrl = ''
          if (self.ruleForm.thumbSrc.length > 0) {
            for (var i = 0; i < self.ruleForm.thumbSrc.length; i++) {
              if (i === 0) {
                picUrl = picUrl + self.ruleForm.thumbSrc[i].response.data
              } else {
                picUrl = picUrl + ',' + self.ruleForm.thumbSrc[i].response.data
              }
            }
          }
          var needData = {}
          needData.picName = picUrl
          needData.type = this.thumbSrcProp.type
          DeletePic(needData).then(res => {
            console.log(res)
          })
        }
        this.eventTab('', 'first')
      },
      // 获取图片上传路径
      getPictureUrl(fileList) {
        this.ruleForm.thumbSrc = fileList
        console.log(fileList)
      },
      // 新增信息发布
      addPublishEvent() {
        var self = this
        if (!this.addFlag) {
          return
        }
        this.$refs.PublishForm.validate(function(valid) {
          if (valid) {
            var needData = {}
            needData.sortCode = self.ruleForm.sortCode
            if (self.ruleForm.sortCode.length > 0) {
              needData.sortCode = self.ruleForm.sortCode[self.ruleForm.sortCode.length - 1]
            }
            needData.title = self.ruleForm.title
            needData.keyword = self.ruleForm.keyword
            needData.orderId = self.ruleForm.orderId
            needData.resume = self.ruleForm.resume
            needData.isActivity = self.ruleForm.isActivity
            needData.content = self.ruleForm.content
            needData.tagNames = self.ruleForm.tagNames.toString()
            var picUrl = ''
            if (self.ruleForm.thumbSrc.length > 0) {
              for (var i = 0; i < self.ruleForm.thumbSrc.length; i++) {
                if (i === 0) {
                  picUrl = picUrl + self.ruleForm.thumbSrc[i].response.data
                } else {
                  picUrl = picUrl + ',' + self.ruleForm.thumbSrc[i].response.data
                }
              }
            }
            needData.thumbSrc = picUrl
            self.addFlag = false
            AddOrUpdatePublishInfo(needData).then(res => {
              if (res.code === 200) {
                self.$message.success(res.message)
                setTimeout(function() {
                  self.eventTab('refresh', 'first', 'publish')
                }, 500)
              } else {
                self.$message.error(res.message)
              }
            })
          } else {
            return
          }
        })
        setTimeout(function() {
          self.addFlag = true
        }, 3000)
      },
      // 编辑
      editPublishEvent() {
        var self = this
        if (!this.addFlag) {
          return
        }
        this.$refs.PublishForm.validate(function(valid) {
          if (valid) {
            var needData = {}
            needData.title = self.ruleForm.title
            needData.resume = self.ruleForm.resume
            needData.keyword = self.ruleForm.keyword
            needData.orderId = self.ruleForm.orderId
            needData.isActivity = self.ruleForm.isActivity
            needData.id = self.editData.id
            needData.content = self.ruleForm.content
            needData.tagNames = self.ruleForm.tagNames.toString()
            console.log(self.ruleForm.sortCode)
            if (self.ruleForm.sortCode.length > 0) {
              needData.sortCode = self.ruleForm.sortCode[self.ruleForm.sortCode.length - 1]
            }
            var picUrl = ''
            if (self.ruleForm.thumbSrc.length > 0) {
              for (var i = 0; i < self.ruleForm.thumbSrc.length; i++) {
                var thisUrl = ''
                if (self.ruleForm.thumbSrc[i].response && self.ruleForm.thumbSrc[i].response.data) {
                  thisUrl = self.ruleForm.thumbSrc[i].response.data
                } else {
                  thisUrl = self.ruleForm.thumbSrc[i].url
                }
                if (i === 0) {
                  picUrl = picUrl + thisUrl
                } else {
                  picUrl = picUrl + ',' + thisUrl
                }
              }
            }
            needData.thumbSrc = picUrl
            self.addFlag = false
            AddOrUpdatePublishInfo(needData).then(res => {
              if (res.code === 200) {
                self.$message.success(res.message)
                setTimeout(function() {
                  self.eventTab('update', 'first', 'publish')
                }, 500)
              } else {
                self.$message.error(res.message)
              }
            })
          } else {
            return
          }
        })
        setTimeout(function() {
          self.addFlag = true
        }, 3000)
      },
      // 富文本
      onEditorBlur(editor) {
        // console.log(this.ruleForm.content)
      },
      onEditorFocus(editor) {
        // console.log('editor focus!', editor)
      },
      onEditorReady(editor) {
        // console.log('editor ready!', editor)
      },
      onEditorChange({ editor, html, text }) {
        this.ruleForm.content = html
      },
      // 富文本图片上传前
      beforeUpload() {
        // 显示loading动画
        this.quillUpdateImg = true
      },
      uploadSuccess(res, file) {
        // res为图片服务器返回的数据
        // 获取富文本组件实例
        const quill = this.$refs.myQuillEditor.quill
        // 如果上传成功
        if (res.code === 200 && res.data) {
          // 获取光标所在位置
          const length = quill.getSelection().index
          // 插入图片  res.info为服务器返回的图片地址
          quill.insertEmbed(length, 'image', res.data)
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          this.$message.error('图片插入失败')
        }
        // loading动画消失
        this.quillUpdateImg = false
      },
      // 富文本图片上传失败
      uploadError() {
        // loading动画消失
        this.quillUpdateImg = false
        this.$message.error('图片插入失败')
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  @import "src/styles/info.scss";
</style>
